﻿using SqlSugar;
using Fortunate.IService;
using Fortunate.Common.Extensions;
using Fortunate.Service.BASE;
using Fortunate.ViewModel;
using Fortunate.ViewModel.UserModule;
using Fortunate.Application.Entities;
using Fortunate.Common;

namespace Fortunate.Service
{
    public class UsersService : BaseServices<Users>, IUsersService
    {
        public UsersService(ISqlSugarClient _db) : base(_db)
        {
        }

        /// <summary>
        /// 获取用户信息列表
        /// </summary>
        /// <returns></returns>
        public async Task<DataModel<Users>> GetUsersListAsync(UsersSearch search)
        {
            DataModel<Users> dataModel = new DataModel<Users>();
            RefAsync<int> total = 0;
            dataModel.Data = await db.Queryable<Users>().OrderBy(x => Convert.ToDateTime(x.CreateTime)).ToPageListAsync(search.PageIndex, search.PageCount, total);
            dataModel.Total = total.Value;
            return dataModel;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        public async Task<Users> GetUsersObjectAsync(Guid id)
        {
            return await db.Queryable<Users>().FirstAsync(x => x.Id == id);
        }

        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <param name="users"></param>
        /// <returns></returns>
        public async Task<bool> InsertUsersAsync(Users users)
        {
            return await db.Insertable(users).ExecuteCommandAsync() > 0;
        }

        /// <summary>
        /// 编辑用户信息
        /// </summary>
        /// <param name="users"></param>
        /// <returns></returns>
        public async Task<bool> UpdateUsersAsync(Users users)
        {
            return await db.Updateable(users).IgnoreColumns(x => x.CreateTime).WhereColumns(x => x.Id).ExecuteCommandAsync() > 0;
        }

        /// <summary>
        /// 冻结账号
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<bool> DeleteUsersAsync(UserInput input)
        {
            var entity = await db.Queryable<Users>().FirstAsync(x => x.Id == input.Id.ToGuid());
            entity.UserState = (int)UserState.冻结;
            return await db.Updateable(entity).UpdateColumns(x => x.UserState).WhereColumns(x => x.Id).ExecuteCommandAsync() > 0;
        }
    }
}
